//
//  ViewController.swift
//  app路由
//
//  Created by zhaoguoteng on 2020/4/27.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

import FMDB
import UIKit

class HomeViewController: UIViewController {
    var dataList = [Route]()
    var editRoute: Route?
    
    @IBOutlet var tableView: UITableView!
    var refreshControl: UIRefreshControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        loadDBData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadDBData()
    }
    
    func setupView() {
        refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refreshAction), for: .valueChanged)
        tableView.addSubview(refreshControl)
    }
    
    @objc func refreshAction() {
        loadDBData()
        refreshControl.endRefreshing()
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let addVC = segue.destination as? AddViewController {
            addVC.route = self.editRoute
            self.editRoute = nil
        } else if let scanVC = segue.destination as? ScancodeViewController {
            scanVC.dismissBlock = { [weak self] in
                guard let self = self else {
                    return
                }
                self.loadDBData()
            }
        } else if let qrCodePreviewVC = segue.destination as? QRCodePreviewViewController {
            do {
                var qrRoute = self.editRoute
                self.editRoute = nil
                qrRoute?.img = nil
                
                let jsonData = try JSONEncoder().encode(qrRoute)
                let jsonString = String(data: jsonData, encoding: .utf8)
                qrCodePreviewVC.qrText = jsonString
            } catch {
                fatalError(error.localizedDescription)
            }
        }
    }
}

/// db handle
extension HomeViewController {
    func loadDBData() {
       
        // 创建表
        SqliteManager.createTable()
        
        // 查询
        SqliteManager.queryData(sql: "select * from routes order by date DESC") { [weak self] (res: [Route]) in
            guard let self = self else { return }
            
            self.dataList.removeAll()
            for item in res {
                self.dataList.append(item)
            }
            
            self.tableView.reloadData()
        }
        
        // 清除多余图片
        ImageFileManager.removeUnnecessaryImages()
    }
}

extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
        cell.route = dataList[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let route = dataList[indexPath.row]
        
        guard let url = route.url, let appUrl = URL(string: url) else {
            return
        }
        
        UIApplication.shared.open(appUrl, options: [:], completionHandler: nil)
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let route = dataList[indexPath.row]
        
        let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] _, _, _ in
            
            guard let self = self else { return }
            
            if let rid = route.rid, let dbQueue = SqliteManager.shareDBQ {
                dbQueue.inDatabase { db in
                    do {
                        try db.executeUpdate("delete from routes where rid = '\(rid)'", values: nil)
                        self.dataList.remove(at: indexPath.row)
                        ImageFileManager.removeImageWithFileName(fileName: route.img)
                    } catch {
                        fatalError(error.localizedDescription)
                    }
                    
                    OperationQueue.main.addOperation {
                        tableView.reloadData()
                    }
                }
            }
        }
        
        let editAction = UIContextualAction(style: .normal, title: "编辑") { [weak self] _, _, _ in
            guard let self = self else { return }
            
            self.editRoute = route
            self.performSegue(withIdentifier: "add", sender: self)
        }
        editAction.backgroundColor = .blue
        
        let erCodeAction = UIContextualAction(style: .normal, title: "二维码") { [weak self] _, _, block in
            guard let self = self else { return }
            
            self.editRoute = route
            self.performSegue(withIdentifier: "QRCodePreviewViewController", sender: self)
            block(true)
        }
        erCodeAction.backgroundColor = .black
        
        let configuration = UISwipeActionsConfiguration(actions: [deleteAction, editAction, erCodeAction])
        return configuration
    }
}
